import { showToast } from "@/utils/showToast";
import hl from "highlight.js"; // 导入代码高亮文件
import { RefObject, useEffect, useRef } from "react";

// 自定义一个代码高亮指令
const createCopy = (el: HTMLElement) => {
  //插入复制功能
  const code = el.getElementsByTagName("code")[0];
  const copy = document.createElement("div");
  copy.classList.add("hljs-copy");
  const lang = el.getElementsByTagName("table")[0];
  const langText = lang.dataset.lang;
  copy.innerHTML = `<span class="lang-box">${langText}</span> <span class="iconfont icon-xinAPPtubiaoPython_bianjiqi copy-box"></span>`;
  //添加点击事件
  copy.addEventListener("click", () => {
    //创建一个输入框
    const textarea = document.createElement("textarea");
    document.body.appendChild(textarea);
    textarea.setAttribute("readonly", "readonly");
    textarea.value = code.innerText;
    textarea.select();
    if (document.execCommand("copy")) {
      document.execCommand("copy");
      //   copy.innerHTML = "<span>复制成功</span>";
        showToast("复制成功!");
    }
    document.body.removeChild(textarea);
  });

  el.insertBefore(copy, el.firstChild);

  //   //鼠标移入显示复制按钮
  //   code.addEventListener("mouseout", () => {
  //     copy.innerText = "复制";
  //     copy.style.display = "none";
  //   });
  //   code.addEventListener("mouseover", () => {
  //     copy.style.display = "block";
  //   });
};

export default function useCopyCode(): {
  mardownRef: RefObject<HTMLDivElement>;
} {
  const mardownRef = useRef<HTMLDivElement>(null);

  const copy = () => {
    if (!mardownRef.current) return;
    const blocks: HTMLElement[] = [
      ...mardownRef.current.querySelectorAll("pre code"),
    ] as HTMLElement[];
    blocks.forEach((block) => {
      hl.highlightBlock(block);
      block.parentElement && createCopy(block.parentElement);
    });
  };
  useEffect(() => {
    mardownRef.current && copy();
  });
  return {
    mardownRef,
  };
}
